﻿// Copyright (c) 2025 liucl
// Inject is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan
// PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//          http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO
// NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.

#include "win_proc.hpp"
#include "core/enum_wnd.hpp"
#include "core/sub_wnd.hpp"
#include "singleton.hpp"

void WinProc::attach() {
  WNDS wnds;
  if (enum_windows(wnds)) {
    for (auto hwnd : wnds) {
      if (::IsWindow(hwnd)) {
        // 使用ATL设施修改proc
        SubWin *subWin = new SubWin();
        // 保存原始proc并设置新的窗口过程
        if (subWin->SubclassWindow(hwnd)) {
          // 保存子类化的窗口引用
          subclassedWindows.push_back(subWin);
        }
      }
    }
  }
}

void WinProc::unattach() {
  for (auto &window : subclassedWindows) {
    if (window->IsWindow()) {
      // 恢复原始窗口过程
      window->UnsubclassWindow();
    }
    delete window;
  }
  subclassedWindows.clear();
}

#define attach() Singleton<WinProc>::instance().attach()
#define unattach() Singleton<WinProc>::instance().unattach()

#include "dllmain.hpp"
